﻿using Microsoft.AspNetCore.Mvc;
using MVC.Models;
using MVC.Models.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MVC.Controllers
{
    public class aregisterController : Controller
    {
        private readonly LifengContext _context;
        public aregisterController(LifengContext context)
        {
            _context = context;
        }
        [Route("/[controller]")]
        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        [Route("/api/admin")]
        public ApiModel Aregister(Aregister request)
        {
            // return Json(request);
            // 1.判断用户名是否存在
            if (_context.Admins.Where(u => u.AdminName == request.AdminName).Count() > 0)
            {
                return new ApiModel { status = "error", data = "用户名已存在,请更换用户名后重试" };
            }
            // 生成随机数作为用户id
            Random random = new Random();
            // 创建用户模型
            var model = new Admin
            {
                AdminId = random.Next(1, 999),
                AdminName = request.AdminName,
                AdminPassword = request.AdminPassword,
            };
            // 3.添加用户
            _context.Admins.Add(model);
            // 4.保存到数据库
            // 判断是否添加成功
            if (_context.SaveChanges() > 0)
            {
                return new ApiModel { status = "ok", data = "用户添加成功" };
            }
            return new ApiModel { status = "error", data = "用户添加失败" };
        }

        private ApiModel Object(ApiModel apiModel)
        {
            throw new NotImplementedException();
        }
    }
}
